import socket
import threading
import json
import time
import subprocess
import os

exe_path = './LeapMotionPolling.exe'

# 从Leap Motion传感器拿数据

# 全局变量，用于存储解析后的数据
global_data = {}
thread_flag = True
pid = None

def handle_client_connection(client_socket):
    global global_data
    buffer = ""
    while True:
        data = client_socket.recv(1024).decode(errors='ignore')  # 接收数据并解码
        if not data:
            break
        buffer += data
        if "\r\n" in buffer:
            json_data, buffer = buffer.split("\r\n", 1)  # 按行分割数据
            try:
                global_data = json.loads(json_data)  # 解析JSON数据
                global_data['t'] = time.time_ns()  # 添加时间戳
            except json.JSONDecodeError as e:
                print(f"Failed to decode JSON: {e}")  # 捕获并打印JSON解析错误

    client_socket.close()  # 关闭客户端连接

def start_server():
    global thread_flag

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建套接字
    server.bind(('127.0.0.1', 8900))  # 绑定IP和端口
    server.listen(5)  # 开始监听
    print("Server started, listening on 127.0.0.1:8900")

    while thread_flag:
        client_sock, address = server.accept()  # 接受客户端连接
        client_handler = threading.Thread(target=handle_client_connection, args=(client_sock,), daemon=True)
        client_handler.start()  # 启动处理客户端连接的线程

# 启动服务器线程
def start_leap_recv_svr():
    global pid
    process = subprocess.Popen([exe_path])  # 启动外部程序
    print(f"Started {exe_path} with PID {process.pid}")
    pid = process.pid  # 记录进程ID
    server_thread = threading.Thread(target=start_server)
    server_thread.daemon = True  # 设置守护线程
    server_thread.start()  # 启动服务器线程
    return server_thread

def stop_leap_recv_svr():
    global pid
    global thread_flag
    thread_flag = False  # 停止服务器循环
    if pid is not None:
        os.kill(pid, 9)  # 杀死外部程序进程
